﻿using System;
using System.Text;
using CRMEntity;
using CRMFramework;

namespace CRMBiz
{
    public static class CmsMemberHandler
    {
        public static CmsMember Login(string userName, string password)
        {
            try
            {
                var p = new[] {
                    DBhelper.SetParameter("@username", userName),
                    DBhelper.SetParameter("@password", password)
                };

                var sbSql = new StringBuilder("SELECT m.*, n.text AS MemberName, n.createDate")
                    .Append(" FROM CmsMember m, UmbracoNode n")
                    .Append(" WHERE m.nodeId = n.id")
                    .Append(" AND m.LoginName=@username")
                    .Append(" AND m.Password=@password");

                var dt = DBhelper.ExecuteDataset(sbSql.ToString(), p).Tables[0];

                if (dt.Rows.Count == 0)
                {
                    return null;
                }

                var entity = new CmsMember();
                var dr = dt.Rows[0];
                entity.NodeID = dr["NodeId"] as int?;
                entity.Email = dr["Email"] as string;
                entity.LoginName = dr["LoginName"] as string;
                entity.MemberName = dr["MemberName"] as string;
                entity.CreateDate = dr["CreateDate"] as DateTime?;

                return entity;
            }
            catch (Exception ex)
            {
                //return ex.Message;
                throw ex;
            }
        }

        public static CmsMember GetByUserName(string userName)
        {
            try
            {
                var p = new[] {
                    DBhelper.SetParameter("@username", userName),
                };

                var sbSql = new StringBuilder("SELECT m.*, n.text AS MemberName, n.createDate")
                    .Append(" FROM CmsMember m, UmbracoNode n")
                    .Append(" WHERE m.nodeId = n.id")
                    .Append(" AND m.LoginName=@username");

                var dt = DBhelper.ExecuteDataset(sbSql.ToString(), p).Tables[0];

                if (dt.Rows.Count == 0)
                {
                    return null;
                }

                var entity = new CmsMember();
                var dr = dt.Rows[0];
                entity.NodeID = dr["NodeId"] as int?;
                entity.Email = dr["Email"] as string;
                entity.LoginName = dr["LoginName"] as string;
                entity.MemberName = dr["MemberName"] as string;
                entity.CreateDate = dr["CreateDate"] as DateTime?;

                return entity;
            }
            catch (Exception ex)
            {
                //return ex.Message;
                throw ex;
            }
        }

    }
}
